<?php

namespace app\api\controller\v1;

use addons\litestore\model\Litestoregoodsspec;
use addons\litestore\model\Wxlitestoregoods;
use addons\wechat\library\Config as ConfigService;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestorenews;
use app\admin\model\Profitorder;
use app\admin\model\Profitorderundo;
use app\admin\model\Profitvip;
use app\admin\model\Publishwork;
use app\admin\model\Shopuser;
use app\admin\model\Usermsgweixin;
use app\admin\model\Userteamworkhistory;
use app\admin\model\Workaddress;
use app\admin\model\Workhistory;
use app\admin\model\Worktype;
use app\api\service\ProfitService;
use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;
use think\Exception;

/**
 */
class Work extends Api
{
    protected $noNeedLogin = ['workType'];
    protected $noNeedRight = ['*'];
    protected $wxapp = null;
    public function _initialize()
    {
        parent::_initialize();


        $this->wxapp = Factory::officialAccount(ConfigService::load());

    }

    public function workType()
    {

        $workTypeModel = new Worktype();
        $list = $workTypeModel->select();
        $this->success('', $list);
    }

    public function workList(){
        $user = $this->auth->getUser();
        $userWorkAddressModel = new Workaddress();
        $list = $userWorkAddressModel->where('uid',$user['id'])->select();
        $this->success('',$list);

    }

    public function addWorkAddress()
    {


        $provinceId = $this->request->param('provinceId');
        $areaId = $this->request->param('areaId');
        $cityId = $this->request->param('cityId');
        $detail = $this->request->param('detail');

        $provinceName = $this->request->param('provinceName');
        $cityName = $this->request->param('cityName');
        $areaName = $this->request->param('areaName');


        $user = $this->auth->getUser();

        $userWorkAddressModel = new Workaddress();
        $id = $userWorkAddressModel->insertGetId([ 'uid' => $user['id'],
            'provinceId' => $provinceId, 'areaId' => $areaId, 'cityId' => $cityId,
            'detail' => $detail,'provinceName'=>$provinceName,'cityName'=>$cityName,'areaName'=>$areaName]);
        if ($id) {
            $this->success('成功',$id);
        } else {
            $this->success('添加失败');
        }

    }


    public function publishWork(){

        $userPublishWorkModel = new Publishwork();
        $worktype = $this->request->param('worktype');
        $worktime = $this->request->param('worktime');
        $addressId = $this->request->param('addressId');
        $money = $this->request->param('money');

        $user = $this->auth->getUser();

        $usrModel = new \app\admin\model\User();
        $user = $usrModel->where('id',$user['id'])->find();
        if($user['type_tag'] == '推广者'){
            $this->error("您是推广者，无法发布工作");
        }

        $userWorkAddressModel= new Workaddress();
        $address = $userWorkAddressModel->where('id',$addressId)->find();

        $data = array();
        $data['uid'] = $user['id'];
        $data['worktype'] = $worktype;
        $data['worktime'] =  strtotime($worktime);
        $data['areaId'] =$address['areaId'];
        $data['areaName'] = $address['areaName'];
        $data['addressId'] = $address['id'];
        $data['createtime'] = time();
        $data['money'] = $money;
        $userPublishWorkModel->insert($data);
        $this->success('成功');

    }

    /**
     * 工作记录
     */
    public function recordWork(){

        $workdId = $this->request->param('workId');
        $endtime = $this->request->param('endTime');
        $clock = $this->request->param('clock');
        if($clock == 0 || $clock*10%5 != 0){
            $this->error('客钟必须是5的倍数');

        }

        $workTypeModel = new Worktype();
        $wok = $workTypeModel->where('id',$workdId)->find();

        $user = $this->auth->getUser();


        $shopUserModel = new Shopuser();
        $shopuser = $shopUserModel->where('uid',$user['id'])->where('status',1)->find();
        if(!$shopuser){
            $this->error('请选择所在公司');
        }
        $data = array();
        $data['uid'] = $user['id'];
        $data['workid'] = $workdId;
        $data['companyid'] = $shopuser['shopId'];
        $data['endtime'] = strtotime($endtime);
        $data['clock'] = $clock;
        $data['backmoney'] = $wok['backmoney']*$clock*0.3;
        $data['total'] = $wok['backmoney']*$clock;


        $workHistoryModel = new Workhistory();
        $id = $workHistoryModel->insertGetId($data);
        if($id > 0){
           $shopId =  $shopuser['shopId'];
           $shopModel = new \app\admin\model\Shop();
           $shop = $shopModel->where('id',$shopId)->find();
           $shopUid = $shop['uid'];
           $usermsgModel = new Usermsgweixin();

            $wx = $usermsgModel->where('user_id',$shopUid)->find();
            if($wx){
                error_log("=====wx======".json_encode($wx));
                $t = $this->wxapp->template_message->send([
                    'touser' => $wx['openid'],
                    'template_id' => 'XtJXVSu634xsrDnt32TYwcioHrEbsRaPc5blfbUZRiE',
                    'data' => [
                        'first' => "有新的订单待处理。",
                        'keyword1' => $user['username'],
                        'keyword2' => "记录了 ".$clock." 客钟 返现金额 ".$wok['backmoney']*$clock*0.3,
                        'remark' => '请及时查看处理',
                    ],
                ]);

            }

            $shopAdminModel = new \app\admin\model\Shopadmin();
            $shopAdmin = $shopAdminModel->where('shopid',$shopId)->find();
            if($shopAdmin){
                $adminWx  = $usermsgModel->where('user_id',$shopAdmin['uid'])->find();
                $t = $this->wxapp->template_message->send([
                    'touser' => $adminWx['openid'],
                    'template_id' => 'XtJXVSu634xsrDnt32TYwcioHrEbsRaPc5blfbUZRiE',
                    'data' => [
                        'first' => "有新的订单待处理。",
                        'keyword1' => $user['username'],
                        'keyword2' => "记录了 ".$clock." 客钟 返现金额 ".$wok['backmoney']*$clock*0.3,
                        'remark' => '请及时查看处理',
                    ],
                ]);
            }

        }



        $this->success('成功');

    }

    //我的工作记录列表
    public function myworkList(){

        $page = $this->request->param('page');
        $date = $this->request->param('date');
        $uid = $this->request->param('uid');

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        $user = $this->auth->getUser();

        if(!$uid){
            $uid = $user['id'];
        }

        if($date != ''){
            $startToday = strtotime($date . " 00:00:00");
            $endToday = strtotime($date . " 23:59:59");

//            $where['endtime']=array('>=',$startToday);
//            $where['endtime']=array('<=',$endToday);


        }

        $workhistoryModel = new Workhistory();



        $clock = $workhistoryModel->where($where)->where("uid",$uid)->where('status',1)->sum('clock');
        $money = $workhistoryModel->where($where)->where("uid",$uid)->where('status',1)->sum('backmoney');
        $total = $workhistoryModel->where($where)->where("uid",$uid)->where('status',1)->sum('total');

        $data = array();
        $data['money'] = $money;
        $data['clock'] = $clock;
        $data['total'] = $total;


        $list = $workhistoryModel->with(['company','worktype'])
            ->where($where)
            ->where("Workhistory.uid",$uid)
            ->order(['endtime' => 'desc'])->limit($offset, $limit)
            ->select();
        foreach ($list as $key=>$val){
            $list[$key]['endtime'] = date('Y-m-d H:i:s',$val['endtime']);
        }

        $data['list'] = $list;

        $this->success('成功',$data);
    }


    public function teamWorkHistory(){

        $user = $this->auth->getUser();
        $teamWorkHistoryModel = new Userteamworkhistory();
        $totalClock = $teamWorkHistoryModel->where('uid',$user['id'])->sum('clock');
        $totalAmount = $teamWorkHistoryModel->where('uid',$user['id'])->sum('backMoney');

        $page = $this->request->param('page');

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $userModel = new \app\admin\model\User();

        $where = array();
        $where['ref_uid'] = $user['id'];

        $list = $userModel
            ->where($where)
            ->order(['createtime' => 'desc'])->limit($offset, $limit)
            ->select();
        foreach ($list as $key => $val) {
            if ($val['group_id'] == 1) {
                $list[$key]['group_name'] = '普通用户';
            }
            $list[$key]['createtime'] = date('Y-m-d',$val['createtime']);
            if (strpos($val['username'], "o") === 0) {
                $list[$key]['username'] = '未实名';
            }

            $t = $teamWorkHistoryModel->where('workUserId',$val['id'])->sum('backmoney');

            error_log($val['username']."========".$val['id']);
            $list[$key]['amount'] = $t;

        }
        $data = array();
        $data['totalClock'] = $totalClock;
        $data['totalAmount'] = $totalAmount;
        $data['list'] = $list;

        $this->success('',$data);
    }


    public function getWorkType(){
        $user = $this->auth->getUser();
        if($user['work_type'] == -1){
            $this->error('请联系客服');
        }
        $workTypeModel = new Worktype();
        $workType = $workTypeModel->where('id',$user['work_type'])->find();
        $this->success('成功',$workType);
    }

    public function deleteWorkHistory(){

        $id = $this->request->param('id');
        $workHistoryModel = new Workhistory();
        $work = $workHistoryModel->where('id',$id)->find();
        $user = $this->auth->getUser();
        if($user['id'] != $work['uid']){
            $this->error('暂无权限操作');
        }
        if($work['status']  != -1){
            $this->error('此数据状态不允许操作');
        }

        $workHistoryModel->where('id',$id)->delete();
        $this->success('操作成功');
    }

}
